package com.ujiuye.demo;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
    public static void main1(String[] args) throws IOException {
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet();
        //索引从0开始
        XSSFRow row = sheet.createRow(2);
        XSSFCell cell = row.createCell(2);
        cell.setCellValue("测试");

        FileOutputStream fos = new FileOutputStream("C:\\Users\\Saul.J.Wu\\Desktop\\demo.xlsx");
        wb.write(fos);
        fos.close();

    }

    public static void main2(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("C:\\Users\\Saul.J.Wu\\Desktop\\demo.xlsx");
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet sheet = wb.getSheetAt(0);
        XSSFRow row = sheet.getRow(2);
        XSSFCell cell = row.getCell(2);
        String value = cell.getStringCellValue();
        System.out.println(value);
        fis.close();
    }

    public static void main3(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("C:\\Users\\Saul.J.Wu\\Desktop\\demo.xlsx");
        Workbook wb = WorkbookFactory.create(fis);
        Sheet sheet = wb.getSheetAt(0);
        Row row = sheet.getRow(2);
        Cell cell = row.getCell(2);
        String value = cell.getStringCellValue();
        System.out.println(value);
        fis.close();
    }

    public static void main4(String[] args) throws IOException {
        String filePath = "C:\\Users\\Saul.J.Wu\\Desktop\\demo.xlsx";
        FileInputStream fis = new FileInputStream(filePath);
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet sheet = wb.getSheetAt(0);
        //物理行数
        int rows = sheet.getPhysicalNumberOfRows();
        for (int i = 0; i < rows; i++) {
            XSSFRow row = sheet.getRow(i);
            //获取当前行的单元格的数量
            int cells = row.getPhysicalNumberOfCells();
            for (int j = 0; j < cells; j++) {
                XSSFCell cell = row.getCell(j);
                String value = cell.getStringCellValue();
                System.out.println(value+" ");
            }
            System.out.println();
        }
    }

}
